package com.ikingtech.platform.service.system.dept.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.iking.framework.sdk.authorization.api.AuthorizationDeptApi;
import com.ikingtech.framework.sdk.context.security.Me;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.dept.entity.DepartmentDO;
import com.ikingtech.platform.service.system.dept.service.repository.DeptRepository;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class AuthorizationDeptService implements AuthorizationDeptApi {

    private final DeptRepository repo;

    /**
     * 加载所有部门的完整路径列表
     *
     * @return 部门完整路径列表
     */
    @Override
    public List<String> loadFullPathAll() {
        return this.repo.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                .select(DepartmentDO::getFullPath)
                .eq(DepartmentDO::getTenantCode, Me.tenantCode()));
    }

    /**
     * 根据部门ID列表加载完整路径列表
     * @param deptIds 部门ID列表
     * @return 完整路径列表
     */
    @Override
    public List<String> loadFullPathByDeptIds(List<String> deptIds) {
        // 如果部门ID列表为空，则返回空列表
        if (Tools.Coll.isBlank(deptIds)) {
            return new ArrayList<>();
        }
        // 使用lambdaQuery方法构建查询条件
        return this.repo.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                .select(DepartmentDO::getFullPath)
                .in(DepartmentDO::getId, deptIds)
                .eq(DepartmentDO::getTenantCode, Me.tenantCode()));
    }

    /**
     * 根据部门ID列表加载子部门的完整路径列表
     *
     * @param deptIds 部门ID列表
     * @return 子部门的完整路径列表
     */
    @Override
    public List<String> loadSubFullPathByDeptIds(List<String> deptIds) {
        // 调用loadFullPathByDeptIds方法加载部门的完整路径列表
        List<String> fullPaths = this.loadFullPathByDeptIds(deptIds);
        // 如果完整路径列表为空，则返回空列表
        if (Tools.Coll.isBlank(fullPaths)) {
            return new ArrayList<>();
        }
        // 调用repo的listObjs方法查询DepartmentDO对象列表
        return this.repo.listObjs(Wrappers.<DepartmentDO>lambdaQuery()
                // 选择DepartmentDO对象的getFullPath属性
                .select(DepartmentDO::getFullPath)
                // 使用or方法构建逻辑或条件
                .and(wrapper -> fullPaths.forEach(fullPath -> wrapper.or().likeRight(DepartmentDO::getFullPath, fullPath)))
                // 等于DepartmentDO对象的getTenantCode属性为Me.tenantCode()
                .eq(DepartmentDO::getTenantCode, Me.tenantCode()));
    }
}
